package com.rtx.api.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    /**
     * jwt 密钥
     */
    private static final String SECRET = "1qaz2wsx";

    /**
     * 过期时间ms
     */
    //private static final long EXPIRE_TIME = 5 * 60 * 1000;
    private static final long EXPIRE_TIME = 60 * 60 * 1000;

    /**
     * 生成token
     */
    public static String getToken(Map<String,Object> map){
        Date nowDate = new Date();
        //创建jwt builder
        JwtBuilder builder = Jwts.builder();
        String token = builder.setHeaderParam("type", "JWT")
                .setIssuedAt(nowDate)
                .setSubject("API")
                .setExpiration(new Date(nowDate.getTime() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .addClaims(map)
                .compact();
        return token;
    }

    /**
     * 获取token中注册信息
     * @param token
     * @return
     */
    public static Claims getTokenClaim (String token) {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 验证token是否过期失效
     * @param expirationTime
     * @return
     */
    public static boolean isTokenExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 获取token失效时间
     * @param token
     * @return
     */
    public static Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }

    /**
     * 获取用户名从token中
     */
    public static String getUsernameFromToken(String token) {
        return getTokenClaim(token).getSubject();
    }

    /**
     * 获取jwt发布时间
     */
    public static Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }

    /**
     * 获取自定义值从token中
     */
    public static Object getUsernameFromToken(String token,String key) {
        return getTokenClaim(token).get(key);
    }
}
